package com.zzu.servlet;

import com.zzu.model.Manager;
import com.zzu.model.Student;
import com.zzu.service.ManagerService;
import com.zzu.service.StudentService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/ManagerServlet")
public class ManagerServlet extends HttpServlet {

    private ManagerService managerService = new ManagerService();
    private StudentService studentService = new StudentService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String param = request.getParameter("param");
        PrintWriter out = response.getWriter();
        if("managerInfo".equals(param)){
            //跳转到管理员信息页面，查询管理员信息，通过request传进去
            String id = request.getParameter("id");
            Manager manager = managerService.findManagerById(id);
            //将josn对象传到jsp
            JSONObject json = JSONObject.fromObject(manager);//将java对象转换为json对象
            String str = json.toString();//将json对象转换为字符串
            out.println(str);
        }else if("studentInfo".equals(param)){
            //查询全部学生信息
            List<Student> studentList = studentService.findAllStudents();
            //转成json对象
            JSONArray jsonArray = JSONArray.fromObject(studentList);
            out.println(jsonArray);
        }else if("studentDelete".equals(param)){
            //删除学生操作，获取id
            String id = request.getParameter("id");
            if(studentService.deleteStudent(id)){
                //删除成功
                response.sendRedirect("manager_student_info.jsp");
            }else{
                //删除失败
            }
        }
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
